﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GAM_Web_Designer_Pro.Properties;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace GAM_Web_Designer_Pro {
    public static class ProjectAccess {

        /// <summary>
        /// Saves the project.
        /// </summary>
        /// <param name="project">The project to save</param>
        /// <param name="path">The path where to save</param>
        public static void SaveProject( Project project, string path ) {
            try {
                // Check to see if the path has the projects extension.
                if ( !path.EndsWith( Settings.Default.ProjectExt ) )
                    path += Settings.Default.ProjectExt;

                // Open a stream to the path so we can write to it.
                FileStream stream = File.OpenWrite( path );
                BinaryFormatter formatter = new BinaryFormatter();
                // Serialize the project to save it.
                formatter.Serialize( stream, path );
                // Close the stream.
                stream.Close();
            }
            catch ( Exception e ) {
                new BugReporter.BugReporterForm( Application.ProductName,
                    Application.ProductVersion, e.ToString(), e.Message ).Show();
            }
        }

        /// <summary>
        /// Loads a project
        /// </summary>
        public static Project LoadProject(string path) {
            Project project = new Project();

            try {

                FileStream stream;
                BinaryFormatter formatter = new BinaryFormatter();
                
                stream = File.OpenRead(path);
                project = (Project)formatter.Deserialize( stream );
                stream.Close();

                return project;
            }
            catch ( Exception e ) {
                new BugReporter.BugReporterForm( Application.ProductName,
                    Application.ProductVersion, e.ToString(), e.Message ).Show();
            }

            return project;
        }
    }
}
